package com.jxx.aop;

import com.jxx.anno.CacheFind;
import com.jxx.util.ObjectMapperUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

@Aspect //标识我是一个切面
@Component  //交给spring容器管理
public class CacheAOP {
    @Autowired(required = false)
    private JedisCluster jedis; //完成集群的注入

    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint joinPoint, CacheFind cacheFind){
        try {
            Object result = null;
            String key = cacheFind.preKey();
            if (jedis.exists(key)){
                String json = jedis.get(key);
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                Class returnType = methodSignature.getReturnType();
                result = ObjectMapperUtil.toObject(json,returnType);
                System.out.println("AOP查询redis缓存");
            }else {
                result = joinPoint.proceed();
                String json = ObjectMapperUtil.toJSON(result);
                if (cacheFind.seconds()>0){
                    jedis.setex(key, cacheFind.seconds(), json);
                }else {
                    jedis.set(key, json);
                }
                System.out.println("AOP查询数据库");
            }
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException(throwable);
        }
    }
}
